import {
  Streamlit,
  withStreamlitConnection,
  StreamlitComponentBase
} from "streamlit-component-lib"
import React from "react"

// 定义参数接口
interface PythonArgs {
  name: string;
  disabled: boolean;
}

interface State {
  hovered: boolean;
  focused: boolean;
}

/**
 * This is a React-based component template. The passed props are coming from the 
 * Streamlit library. Your custom args can be accessed via the `args` props.
 */
class PasteComponent extends StreamlitComponentBase<State, PythonArgs> {
  state: State = {
    hovered: false,
    focused: false
  };

  async handleClick() {
    const text = await navigator.clipboard.readText();
    const timestamp = Date.now()
    Streamlit.setComponentValue({"text": text, "timestamp": timestamp})
  }

  getStyles() {
    // 提供默认主题值
    const defaultTheme = {
      primaryColor: "#ff4b4b",
      backgroundColor: "#0e1117",
      secondaryBackgroundColor: "#262730",
      borderColor: "rgba(250, 250, 250, 0.2)",
      textColor: "#fafafa",
      font: "-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif",
    };

    // 从 props 中安全地获取主题值
    const theme = this.props.theme || defaultTheme;
    return {
      button: {
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        fontWeight: 400,
        padding: "0.25rem 0.75rem",
        borderRadius: "0.5rem",
        minHeight: "2.5rem",
        margin: "0px",
        lineHeight: 1.6,
        backgroundColor: theme.backgroundColor,
        border: `1px solid ${this.state.hovered ? theme.primaryColor : (theme as any).borderColor}`,
        color: this.state.hovered ? theme.primaryColor : theme.textColor,
      }
    };
  }

  render() {
    const styles = this.getStyles();
    const { name, disabled } = this.props.args;

    return (
      <button
        onClick={() => this.handleClick()}
        onMouseEnter={() => this.setState({ hovered: true })}
        onMouseLeave={() => this.setState({ hovered: false })}
        onFocus={() => this.setState({ focused: true })}
        onBlur={() => this.setState({ focused: false })}
        disabled={disabled}
        style={styles.button as React.CSSProperties}
      >
        {name}
      </button>
    );
  }
}

// "withStreamlitConnection" is a wrapper function. It bootstraps the
// connection between your component and the Streamlit app, and handles
// passing arguments from Python -> Component.
//
// You don't need to edit withStreamlitConnection (but you're welcome to!).
export default withStreamlitConnection(PasteComponent)
